/**
 * 
 */
package com.hk.web.controller.pc;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hk.commons.vo.ProductInfoRes;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.ProductInfoPhoneRes;
import com.hk.Mgr.web.message.order.ProductInfoReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.Constant;
import com.hk.commons.ConstantProduct;
import com.hk.commons.HqlFilter;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.service.kyc.IAgreement;
import com.hk.service.product.ICompany;
import com.hk.service.product.IProductInfo;
import com.hk.service.product.IProductParInfo;
import com.hk.service.sys.IAnswer;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;

/**
 * @author psx 产品信息实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.PC + "/productInfoCtrl")
public class PcProductInfoCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(PcProductInfoCtrl.class);

	@Autowired
	private IProductInfo productInfoService;

	@Autowired
	private ICompany companyService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private IAnswer anService;

	@Autowired
	private ISysUserRoles userRoleService;

	@Autowired
	private IProductParInfo proParService;

	@Autowired
	private IAgreement aggService;

	/**
	 * 
	 * @Title: getProductInfoList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getList", method = RequestMethod.POST)
	public ResponseBase<List<ProductInfoRes>> getList(
			@RequestBody ProductInfoPhoneRes req) {
		ResponseBase<List<ProductInfoRes>> resp = new ResponseBase<List<ProductInfoRes>>();

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and isParent = 0");

		logger.info("pc getProductList params:" + " prodTopType = "
				+ req.getProdTopType() + " prodType = " + req.getProdType()
				+ " hotSale = " + req.getHotSale());

		// 产品一级类型
		if (StringUtils.isNotEmpty(req.getProdTopType())) {
			hqlFilter.addEQFilter("prodTopType",
					Integer.valueOf(req.getProdTopType()));
		}

		// 是否热销
		if (StringUtils.isNotEmpty(req.getHotSale())) {
			hqlFilter.addEQFilter("hotSale", Integer.valueOf(req.getHotSale()));
		}



		hqlFilter.addEQFilter("proStatus",
				ConstantProduct.PRODUCT_RELEASE_STATE_TRUE);

		Long userId = req.getUserId();
		if (userId == null || userRoleService.isTester(userId) == false) {
			hqlFilter.addSql(" and isTest = " + ConstantProduct.PRODUCT_TYPE_NO_TEST);
		}

		hqlFilter.addSql(" and isParent = 0 ");

		// 升序排列
		hqlFilter.addSort("sequence");

		Integer curpage = Integer.valueOf(req.getCurPage());
		Integer pageSize = Integer.valueOf(req.getPageSize());

		if (curpage == null || pageSize == null) {
			resp.setSize(0);
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数错误");
			return resp;
		}

		try {
			List<ProductInfo> productInfoList = productInfoService
					.findByFilter(hqlFilter, curpage, pageSize);

			List<ProductInfoRes> respList = new ArrayList<ProductInfoRes>();

			// 根据模块id查询资源
			if (productInfoList != null && productInfoList.size() > 0) {
				ProductInfoRes singleResp = null;

				for (ProductInfo productInfo : productInfoList) {
					singleResp = productInfoService.getProductInfoResById(productInfo.getId());
					if (singleResp != null) {
						respList.add(singleResp);
					}
				}
				Long total = productInfoService.countByFilter(hqlFilter);
				resp.setSize(total);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setResult(respList);
			} else {
				Long total = Long.valueOf("0");
				resp.setSize(total);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setResult(respList);
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 
	 * @Title: getProductInfoList
	 * @Description: 根据购买型预约型，和父子标获取产品列表
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getListByPar", method = RequestMethod.POST)
	public ResponseBase<List<Map<String, Object>>> getListByPar(
			@RequestBody ProductInfoReq req) {

		Integer buyChannel = req.getBuyChannel();
		Long parId = req.getParId();
		Integer pageSize = req.getPageSize();
		Integer curPage = req.getCurPage();
		logger.info(
				"根据父标获取产品信息，buyChannel = {}, parId={}, pageSize={}, curPage ={}",
				buyChannel, parId, pageSize, curPage);
		// 总体返回内容
		ResponseBase<List<Map<String, Object>>> resp = new ResponseBase<List<Map<String, Object>>>();

		// 根据productInfo, 获得productInfoResList
		List<Map<String, Object>> parRecordList = new ArrayList<Map<String, Object>>();

		// 获取父标
		List<ProductInfo> proParList = new ArrayList<ProductInfo>();
		HqlFilter hqlFilterPar = new HqlFilter();
		hqlFilterPar.addSql(" where 1 = 1 and isParent = 1 and proStatus = 1");
		if (parId == null) {
			if (buyChannel != null) {
				if (buyChannel == 1) {
					// 预约
					hqlFilterPar.addSql(" and  buyChannel = 0)");
				}else if (buyChannel == 2) {
					//购买
					hqlFilterPar.addSql(" and  (buyChannel = 1 or buyChannel = 2)");
				} else if ( buyChannel == 4) {
					//预售
					hqlFilterPar.addSql(" and  buyChannel = 3)");
				}
			}
			//logger.info("hqlFilterPar =  " + hqlFilterPar.getWhereAndOrderHql());
			proParList = productInfoService.findByFilter(hqlFilterPar);
		} else {
			ProductInfo proParInfo = productInfoService
					.findById(parId);
			proParList.add(proParInfo);
		}

		//logger.info("父标的长度为 " + proParList.size());

		for (ProductInfo proParInfo : proParList) {
			HqlFilter hqlFilter = new HqlFilter();

			hqlFilter.addEQFilter("parId", proParInfo.getId());

			hqlFilter.addEQFilter("proStatus",
					ConstantProduct.PRODUCT_RELEASE_STATE_TRUE);

			hqlFilter.addSql(" and isParent = 0 ");

			// 判断用户是否为测试用户，如果不是则只能看到测试产品
			Long userId = req.getUserId();
			if (userId == null || userRoleService.isTester(userId) == false) {
				hqlFilter.addSql(" and isTest = " + ConstantProduct.PRODUCT_TYPE_NO_TEST);
			}else{
				logger.info("the user is tester");
			}


			// 获取子标内容
			//logger.info("proParName = " + proParInfo.getName() + " hqlFilterPar =  " + hqlFilter.getWhereAndOrderHql());

			List<ProductInfo> proList = productInfoService.findByFilter(
					hqlFilter, curPage, pageSize);

			Long subProdSize = productInfoService.countByFilter(hqlFilter);

			//logger.info("proParName = " + proParInfo.getName() + " subSize  =  " + subProdSize.toString());
			if (proList != null && proList.size() > 0) {

				//logger.info("proList size  = " + proList.size());

				Map<String, Object> parRecordMap = new HashMap<String, Object>();
				parRecordMap.put("parId", proParInfo.getId());
				parRecordMap.put("parName", proParInfo.getName());
				parRecordMap.put("financingAccount",
						proParInfo.getFinancingAccount());
				parRecordMap.put("yraiseAccount",
						proParInfo.getYraiseAccount());
				parRecordMap.put("sraiseAccount",
						proParInfo.getSraiseAccount());
				parRecordMap
						.put("minYearRate", proParInfo.getMinYearRate());
				parRecordMap
						.put("maxYearRate", proParInfo.getMaxYearRate());
				parRecordMap.put("riskLevel", proParInfo.getRiskLevel());

				try {
					String proDesc = proParInfo.getName();
					if (proParInfo.getIntroduce() != null) {
						proDesc  = new String(proParInfo.getIntroduce(), "UTF-8");
					}
					parRecordMap.put("proTermStr", proParInfo.getProTermStr());
					parRecordMap.put("proDesc", proDesc);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


				List<Map<String, Object>> proResList = new ArrayList<Map<String, Object>>();

				for (ProductInfo pro : proList) {
					Map<String, Object> proRecordMap = getProInfo(pro.getId());
					proResList.add(proRecordMap);
				}

				parRecordMap.put("productResList", proResList);
				parRecordMap.put("size", subProdSize);
				parRecordList.add(parRecordMap);
			}

		}

		// 设置父标个数
		resp.setSize(parRecordList.size());

		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setResult(parRecordList);

		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/getProductInfoById", method = RequestMethod.POST)
	public ResponseBase<ProductInfoRes> getProductInfoById(
			@RequestBody ProductInfoReq req) {

		Long productId = req.getId();

		logger.info("getProductInfoById productId = " + productId);

		ResponseBase<ProductInfoRes> resp = new ResponseBase<ProductInfoRes>();

		ProductInfoRes prodRes = productInfoService.getProductInfoResById(productId);

		if (prodRes == null || prodRes.getId() == null) {
			resp.setMsg("产品不存在");
			resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
			resp.setResult(prodRes);
		} else {
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(prodRes);
		}

		return resp;
	}

	private Map<String, Object> getProInfo(Long productId) {

		if (productId == null) {
			return null;
		}

		ProductInfo productInfo = productInfoService.findById(productId);
		if (productInfo == null) {
			return null;
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", productInfo.getId());
		map.put("name", productInfo.getName());
		map.put("proTermStr", productInfo.getProTermStr());
		map.put("financingAccount", productInfo.getFinancingAccount());
		map.put("yraiseAccount", productInfo.getYraiseAccount());
		map.put("sraiseAccount", productInfo.getSraiseAccount());
		map.put("minYearRate", productInfo.getMinYearRate());
		map.put("maxYearRate", productInfo.getMaxYearRate());
		map.put("riskLevel", productInfo.getRiskLevel());

		String yearRate = "";
		// 如果是固定收益类
		if (productInfo.getProdTopType().equals(Constant.PRODUCT_TYPE_2)) {
			yearRate = productInfo.getMinYearRate() + " ~ "
					+ productInfo.getMaxYearRate();
		} else if (productInfo.getProdTopType().equals(Constant.PRODUCT_TYPE_3)) {
			yearRate = "浮动收益";
		} else if (productInfo.getProdTopType().equals(Constant.PRODUCT_TYPE_4)) {
			yearRate = "不低于" + productInfo.getMinYearRate();
		}

		map.put("yearRate", yearRate);

		// 剩余额度
		if (productInfo.getSraiseAccount() != null) {

			BigDecimal minSraiseAccount = new BigDecimal("0");
			if (productInfo.getSraiseAccount().compareTo(minSraiseAccount) == -1) {
				map.put("sraiseAccount", minSraiseAccount);
			} else {
				map.put("sraiseAccount", productInfo.getSraiseAccount());
			}
		}

		// 如果满标，则更改已募集额度和剩余额度
		if (productInfo.getSaleOut() != null
				&& productInfo.getSaleOut() == ConstantProduct.PRO_SALE_OUT) {
			BigDecimal minSraiseAccount = new BigDecimal("0");
			// 剩余额度为0
			map.put("sraiseAccount", minSraiseAccount);
			// 已募集额度为总募集
			map.put("yraiseAccount", productInfo.getFinancingAccount());
		}

		return map;
	}
}
